import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

class PhotoViewPage extends StatefulWidget {
  final int index;
  final List<String> imageList;
  const PhotoViewPage(
      {super.key, required this.imageList, required this.index});

  @override
  State<PhotoViewPage> createState() => _PhotoViewPageState();
}

class _PhotoViewPageState extends State<PhotoViewPage> {
  int currentIndex = 0;
  PageController? controller;

  @override
  void initState() {
    super.initState();
    controller = PageController(initialPage: widget.index);
    setState(() {
      currentIndex = widget.index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        iconTheme: const IconThemeData(color: Colors.white),
        elevation: 0,
        title: Text('${currentIndex + 1}/${widget.imageList.length}'),
        backgroundColor: Colors.transparent,
      ),
      body: GestureDetector(
        child: PhotoViewGallery.builder(
          scrollPhysics: const BouncingScrollPhysics(),
          builder: (BuildContext context, int index) {
            return PhotoViewGalleryPageOptions(
              imageProvider:
                  CachedNetworkImageProvider(widget.imageList[index]),
              initialScale: PhotoViewComputedScale.contained * 0.8,
              // heroAttributes: PhotoViewHeroAttributes(tag: imageList[index]),
            );
          },
          pageController: controller,
          itemCount: widget.imageList.length,
          loadingBuilder: (context, event) => Center(
            child: SizedBox(
              width: 20.0,
              height: 20.0,
              child: CircularProgressIndicator(
                value: event == null
                    ? 0
                    : event.expectedTotalBytes == null
                        ? 1
                        : event.cumulativeBytesLoaded /
                            event.expectedTotalBytes!,
              ),
            ),
          ),
          onPageChanged: (index) {
            setState(() {
              currentIndex = index;
            });
          },
        ),
        onTap: () {
          Navigator.pop(context);
        },
      ),
    );
  }
}
